import { useState } from 'react'
import { cn } from '../lib/utils'

interface OptimizedImageProps {
  src: string
  alt: string
  width?: number
  height?: number
  className?: string
  loading?: 'lazy' | 'eager'
  priority?: boolean
}

/**
 * 优化的图片组件
 * - 懒加载
 * - 加载状态
 * - 错误处理
 * - 骨架屏
 */
export function OptimizedImage({
  src,
  alt,
  width,
  height,
  className,
  loading = 'lazy',
  priority = false
}: OptimizedImageProps) {
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState(false)

  return (
    <div className={cn('relative overflow-hidden', className)}>
      {/* 加载骨架屏 */}
      {isLoading && (
        <div className="absolute inset-0 bg-gray-200/20 animate-pulse" />
      )}
      
      {/* 错误状态 */}
      {error ? (
        <div className="absolute inset-0 flex items-center justify-center bg-gray-100/10">
          <div className="text-center">
            <svg className="w-12 h-12 mx-auto text-gray-400 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
            </svg>
            <span className="text-gray-400 text-sm">图片加载失败</span>
          </div>
        </div>
      ) : (
        <img
          src={src}
          alt={alt}
          width={width}
          height={height}
          loading={priority ? 'eager' : loading}
          decoding="async"
          className={cn(
            'transition-opacity duration-300',
            isLoading ? 'opacity-0' : 'opacity-100'
          )}
          onLoad={() => setIsLoading(false)}
          onError={() => {
            setIsLoading(false)
            setError(true)
          }}
        />
      )}
    </div>
  )
}

/**
 * 响应式图片组件
 */
export function ResponsiveImage({
  src,
  alt,
  sizes,
  className
}: {
  src: string
  alt: string
  sizes?: string
  className?: string
}) {
  return (
    <OptimizedImage
      src={src}
      alt={alt}
      className={className}
      loading="lazy"
    />
  )
}

